import React, { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { Tabbar } from '@nutui/nutui-react-taro';
import { useRoleStore, ROLE_TYPES } from '../../store/useRoleStore';
import './index.scss';
import { IconFont } from '@nutui/icons-react-taro';
import chartBar from '../../assets/icon/tabbar/chart-bar.svg';
import tasks from '../../assets/icon/tabbar/tasks.svg';
import bell from '../../assets/icon/tabbar/bell.svg';
import user from '../../assets/icon/tabbar/user.svg';
import robot from '../../assets/icon/tabbar/robot.svg';

import chartBarActive from '../../assets/icon/tabbar/chart-bar-a.svg';
import tasksActive from '../../assets/icon/tabbar/tasks-a.svg';
import bellActive from '../../assets/icon/tabbar/bell-a.svg';
import userActive from '../../assets/icon/tabbar/user-a.svg';
import robotActive from '../../assets/icon/tabbar/robot-a.svg';

// 学生 tabbar 配置
const studentTabs = [
  {
    title: '仪表盘',
    icon: <IconFont name={chartBar} size={20} />,
    activeIcon: <IconFont name={chartBarActive} size={20} />,
    value: 'pages/index/index',
  },
  {
    title: '今日任务',
    icon: <IconFont name={tasks} size={20} />,
    activeIcon: <IconFont name={tasksActive} size={20} />,
    value: 'pages/task/index',
  },
  {
    title: '通知',
    icon: <IconFont name={bell} size={20} />,
    activeIcon: <IconFont name={bellActive} size={20} />,
    value: 'pages/notification/index',
  },
  {
    title: '我的',
    icon: <IconFont name={user} size={20} />,
    activeIcon: <IconFont name={userActive} size={20} />,
    value: 'pages/my/index',
  }
];

// 组长 leader 配置
const leaderTabs = [
  {
    title: '仪表盘',
    icon: <IconFont name={chartBar} size={20} />,
    activeIcon: <IconFont name={chartBarActive} size={20} />,
    value: 'pages/index/index',
  },
  {
    title: '任务管理',
    icon: <IconFont name={robot} size={20} />,
    activeIcon: <IconFont name={robotActive} size={20} />,
    value: 'pages/manage/index',
  },
  {
    title: '通知',
    icon: <IconFont name={bell} size={20} />,
    activeIcon: <IconFont name={bellActive} size={20} />,
    value: 'pages/notification/index',
  },
  {
    title: '我的',
    icon: <IconFont name={user} size={20} />,
    activeIcon: <IconFont name={userActive} size={20} />,
    value: 'pages/my/index',
  }
];

const CustomTabBar = () => {
  const userRole = useRoleStore(state => state.userRole);
  const [activeTab, setActiveTab] = useState(0);
  const tabs = userRole === ROLE_TYPES.LEADER ? leaderTabs : studentTabs;

  // 改进的路由匹配逻辑
  const getActiveTab = () => {
    try {
      const pages = Taro.getCurrentPages();
      const currentPage = pages[pages.length - 1];
      if (!currentPage) return 0;

      const route = currentPage.route || currentPage.__route__;
      // 使用includes进行模糊匹配，增加容错性
      const matchedTab = tabs.findIndex(tab => route.includes(tab.value));
      return matchedTab >= 0 ? matchedTab : 0;
    } catch (error) {
      console.error('获取当前页面失败:', error);
      return 0;
    }
  };

  // 监听页面显示和路由变化
  useEffect(() => {
    const updateActiveTab = () => {
      const currentTab = getActiveTab();
      setActiveTab(currentTab);
    };

    // 页面显示时更新激活状态
    Taro.onAppShow(updateActiveTab);
    // 监听路由变化
    Taro.onAppRoute(updateActiveTab);
    // 初始化时更新一次
    updateActiveTab();

    return () => {
      Taro.offAppShow(updateActiveTab);
      Taro.offAppRoute(updateActiveTab);
    };
  }, []);

  // 改进的页面导航逻辑
  const switchTab = (value) => {
    // 立即更新激活状态，提供即时反馈
    setActiveTab(value);

    try {
      const targetPath = `/${tabs[value].value}`;
      Taro.switchTab({
        url: targetPath,
        fail: (error) => {
          console.error('切换标签页失败:', error);
          // 如果switchTab失败，尝试使用navigateTo
          Taro.navigateTo({
            url: targetPath,
            fail: (err) => {
              console.error('导航失败:', err);
              // 如果导航失败，恢复原来的激活状态
              setActiveTab(getActiveTab());
            }
          });
        }
      });
    } catch (error) {
      console.error('切换标签页出错:', error);
      // 发生错误时恢复原来的激活状态
      setActiveTab(getActiveTab());
    }
  };

  return (
    <Tabbar
      fixed
      value={activeTab}
      onSwitch={switchTab}
      inactiveColor="#7d7e80"
      activeColor="#1989fa"
    >
      {tabs.map((tab, index) => (
        <Tabbar.Item
          key={index}
          title={tab.title}
          icon={activeTab === index ? tab.activeIcon : tab.icon}
        />
      ))}
    </Tabbar>
  );
};

export default CustomTabBar;